<template>
  <el-dialog
    v-model="dialogVisible"
    title="从全局配置创建"
    width="600px"
    :before-close="handleClose">

    <div class="dialog-content">
      <!-- 选择全局配置 -->
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="选择模板" prop="globalConfigId">
          <el-select
            v-model="form.globalConfigId"
            placeholder="请选择全局配置模板"
            style="width: 100%"
            @change="handleConfigChange">
            <el-option
              v-for="config in globalConfigs"
              :key="config.id"
              :label="config.name"
              :value="config.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入新配置的名称" />
        </el-form-item>

        <!-- 配置预览 -->
        <div v-if="selectedConfig" class="config-preview">
          <h6>模板配置预览</h6>
          <div class="preview-content">
            <pre>{{ formatSelectedConfig() }}</pre>
          </div>
        </div>

        <!-- 覆盖配置 -->
        <el-form-item label="自定义覆盖">
          <el-switch v-model="enableOverrides" />
          <span class="help-text">启用后可以覆盖模板中的部分配置</span>
        </el-form-item>

        <div v-if="enableOverrides" class="overrides-section">
          <el-form-item label="购买金额">
            <el-input-number
              v-model="form.overrides.buyAmount"
              :min="0"
              :precision="8"
              placeholder="覆盖购买金额"
              style="width: 100%" />
          </el-form-item>

          <el-form-item label="目标报价">
            <el-input-number
              v-model="form.overrides.targetBuyQuote"
              :min="0"
              :precision="8"
              placeholder="覆盖目标报价"
              style="width: 100%" />
          </el-form-item>

          <el-form-item label="自定义配置">
            <JsonEditor v-model="customConfigJson" :height="120" />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">
          {{ creating ? '创建中...' : '创建配置' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useAccountConfigStore } from '@/store/accountConfig'
import { http } from '@/utils/request'
import { ElMessage } from 'element-plus'
import JsonEditor from './JsonEditor.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  accountId: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'success'])

const accountConfigStore = useAccountConfigStore()

// 状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const creating = ref(false)
const enableOverrides = ref(false)
const globalConfigs = ref([])
const selectedConfig = ref(null)
const customConfigJson = ref('{}')

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  globalConfigId: null,
  configName: '',
  overrides: {
    buyAmount: null,
    targetBuyQuote: null
  }
})

// 表单验证规则
const rules = {
  globalConfigId: [
    { required: true, message: '请选择全局配置模板', trigger: 'change' }
  ],
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { max: 100, message: '配置名称不能超过100个字符', trigger: 'blur' }
  ]
}

// 监听对话框显示
watch(dialogVisible, (visible) => {
  if (visible) {
    loadGlobalConfigs()
    resetForm()
  }
})

// 监听自定义配置JSON变化
watch(customConfigJson, (newValue) => {
  try {
    const parsed = JSON.parse(newValue)
    form.overrides.customConfig = parsed
  } catch (error) {
    // 忽略JSON解析错误
  }
})

// 加载全局配置列表
const loadGlobalConfigs = async () => {
  try {
    const response = await http.get('/configs', { page: 1, size: 100 })
    globalConfigs.value = response.data.list || []
  } catch (error) {
    ElMessage.error('加载全局配置失败')
  }
}

// 配置选择变化
const handleConfigChange = async (configId) => {
  if (!configId) {
    selectedConfig.value = null
    return
  }

  try {
    const response = await http.get(`/configs/${configId}`)
    selectedConfig.value = response.data

    // 自动生成配置名称
    if (!form.configName) {
      form.configName = `基于${selectedConfig.value.name}的配置`
    }
  } catch (error) {
    ElMessage.error('加载配置详情失败')
  }
}

// 格式化选中的配置
const formatSelectedConfig = () => {
  if (!selectedConfig.value) return '{}'

  try {
    const config = JSON.parse(selectedConfig.value.configContent)
    return JSON.stringify(config, null, 2)
  } catch (error) {
    return selectedConfig.value.configContent || '{}'
  }
}

// 创建配置
const handleCreate = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    creating.value = true

    // 构建请求数据
    const requestData = {
      configName: form.configName,
      overrides: {}
    }

    // 添加覆盖配置
    if (enableOverrides.value) {
      if (form.overrides.buyAmount !== null) {
        requestData.overrides.buyAmount = form.overrides.buyAmount
      }
      if (form.overrides.targetBuyQuote !== null) {
        requestData.overrides.targetBuyQuote = form.overrides.targetBuyQuote
      }
      if (form.overrides.customConfig) {
        requestData.overrides.customConfig = form.overrides.customConfig
      }
    }

    await accountConfigStore.createFromGlobalConfig(
      props.accountId,
      form.globalConfigId,
      requestData
    )

    emit('success')
    handleClose()

  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    creating.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    globalConfigId: null,
    configName: '',
    overrides: {
      buyAmount: null,
      targetBuyQuote: null,
      customConfig: null
    }
  })

  enableOverrides.value = false
  selectedConfig.value = null
  customConfigJson.value = '{}'
}
</script>

<style lang="scss" scoped>
.dialog-content {
  .config-preview {
    margin: 16px 0;

    h6 {
      margin: 0 0 8px;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }

    .preview-content {
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 4px;
      padding: 12px;
      max-height: 200px;
      overflow-y: auto;

      pre {
        margin: 0;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 12px;
        line-height: 1.4;
        color: #495057;
      }
    }
  }

  .overrides-section {
    background-color: #f8f9fa;
    border-radius: 4px;
    padding: 16px;
    margin-top: 16px;
  }

  .config-comparison {
    margin-top: 20px;

    h6 {
      margin: 0 0 12px;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }

    .config-block {
      border: 1px solid #e9ecef;
      border-radius: 4px;
      overflow: hidden;

      .block-header {
        padding: 8px 12px;
        background-color: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
      }

      .config-json {
        padding: 12px;
        margin: 0;
        background-color: #fff;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 11px;
        line-height: 1.4;
        color: #495057;
        max-height: 150px;
        overflow-y: auto;
      }
    }
  }

  .help-text {
    margin-left: 8px;
    font-size: 12px;
    color: #909399;
  }
}
</style>